using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using Red.Controls.Shell;
using Red.Controls.Utils;
using Red.Core;

namespace Red.Toolkit.MeshEditor
{
    [Export( typeof( IEditorInfo ) )]
    public class EditorInfo : IEditorInfo
    {
        public string Name
        {
            get { return "Mesh Editor"; }
        }

        public Type WindowClass
        {
            get { return typeof( MeshEditor ); }
        }

        public Type SettingsClass
        {
            get { return typeof( UserSettings ); }
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MeshEditor : RedEditorWindow
    {
        public MeshEditor( IEditorHost host, EditorInstanceData instanceData, EditorSharedData sharedData )
            : base( host, instanceData, sharedData )
        {
            InitializeComponent();
            BackendInitialized += RedMainWindow_BackendInitialized;
        }

        private void RedMainWindow_BackendInitialized( object sender, EventArgs e )
        {
            _materialsTree.Initialize( InstanceData.RootEditorItem.Data );
        }

        private async void ImportBtn_Click( object sender, RoutedEventArgs e )
        {
            List<ResourceFactory.Importer> importers = await SharedData.ResourceFactory.Importers;
            var importer = importers.FirstOrDefault( imp => imp.ClassName == "CMesh" );

            if ( importer == null )
            {
                RedMessageBox.Show( this, RedDialogType.Ok, "No appropriate importers found" );
                return;
            }

            List<string> sourceExtensions = importer.SourceFileDefs.Select( el => string.Format( "{0} (*.{1})|*.{1}", el.Description, el.Extension ) ).ToList();
            var dialog = new Microsoft.Win32.OpenFileDialog
            {
                InitialDirectory = SharedData.DepotInfo.RootPath,
                Multiselect = false,
                Filter = string.Join( "|", sourceExtensions ),
                Title = @"Select source file"
            };

            if ( true.Equals( dialog.ShowDialog() ) )
            {
                string absoluteDestPath = SharedData.DepotInfo.GetAbsolutePath( InstanceData.InstanceContext );

                Result result = await SharedData.ResourceFactory.ReImport( dialog.FileName, absoluteDestPath, importer );
                if ( !result )
                {
                    await ShowErrorAsync( result.Message );
                }
            }

            _structureTree.Refresh();
            _materialsTree.Refresh();
        }
    }
}
